package cn.kgc.springboot.shiro.config;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.RememberMeManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.Cookie;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;


/**
 * @author: mosin
 * @version: v1.0  2023/1/10
 */
@Configuration
public class ShiroConfig {

    // shiroFilter
    @Bean
    public ShiroFilterFactoryBean  shiroFilterFactoryBean(DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //  配置资源的权限
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        // anon  匿名访问  公共资源   authc  需要进行表单认证后才能访问的资源
        map.put("/register.jsp", "anon");
        map.put("/user/register", "anon");
        map.put("/user/login", "anon");
        //map.put("/**", "authc");
        map.put("/**", "user");  //  已经登或者记住我用户可以访问
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        //shiroFilterFactoryBean.setLoginUrl("/login.jsp");
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        return shiroFilterFactoryBean;
    }
    //SecurityManager
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(Realm realm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(realm);
        CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();

        Cookie cookie = new SimpleCookie("rem");
        cookie.setHttpOnly(true);
        cookie.setMaxAge(60);  //  一分钟有效

        cookieRememberMeManager.setCookie(cookie);

        defaultWebSecurityManager.setRememberMeManager(cookieRememberMeManager);
        return defaultWebSecurityManager;
    }

    // realm
    @Bean
    public Realm realm(){
        CustomerRealm customerRealm = new CustomerRealm();
        // 创建MD5凭证匹配器
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher("MD5");
        // 设置散列的次数
        hashedCredentialsMatcher.setHashIterations(50);
        customerRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return customerRealm;
    }

}
